package org.bigdata.framework.admin.web.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.apache.commons.io.FileUtils;
import org.bigdata.framework.admin.web.util.DBUtils;
import org.bigdata.framework.admin.web.util.ExcelMore;
import org.bigdata.framework.admin.web.util.FileDownloadUtil;
import org.bigdata.framework.core.model.BaikeCategory;
import org.bigdata.framework.core.model.BaikeTemplate;
import org.bigdata.framework.core.model.Dict;
import org.bigdata.framework.core.model.DictItem;
import org.bigdata.framework.core.model.GeneralWord;
import org.bigdata.framework.core.model.GeneralWordCategory;
import org.bigdata.framework.core.model.ThesauriWord;
import org.bigdata.framework.core.model.ThesauriWordModule;
import org.bigdata.framework.core.model.ThesauriWordReference;
import org.bigdata.framework.core.model.ThesauriWordRelation;
import org.bigdata.framework.core.model.User;
import org.bigdata.framework.core.protocol.IBaseService;
import org.bigdata.framework.core.protocol.IDynamicService;
import org.bigdata.framework.core.protocol.IPublicService;
import org.bigdata.framework.core.protocol.IWordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.xxl.conf.core.XxlConfClient;

@Controller
public class WordController extends BaseContoroller{
    @Autowired
    private IBaseService baseService;
    @Autowired
    private IPublicService publicService;
    @Autowired
    private IWordService iWordService;
    @Autowired
    private IDynamicService dynamicService;
    
    // 前往叙词表分类页面
    @RequestMapping("word-module-list.html")
    public String toModule() {
        return "/modules/word/word_module_list";
    }
    // 前往叙词表分类页面--->新增或修改
    @RequestMapping("word-module-add-update.html")
    public String toWordModuleAddUpdate() {
        return "/modules/word/word_module_add_update";
    }
    // 前往叙词表模板页面
    @RequestMapping("word-relation-list.html")
    public String toRelation() {
        return "/modules/word/word_relation_list";
    }
    // 前往叙词表模板页面
    @RequestMapping("word-relation-add-upload.html")
    public String toWordRelationAddUpload() {
        return "/modules/word/word_relation_add_upload";
    }
    
    /**
     * @author zf
     * 时间 2017年8月31日16:04:05
     * 词表分类  start
     */
    //查询全部分类
    @RequestMapping("getModuleList")
    public void getModuleList(HttpServletRequest request,HttpServletResponse response) throws Exception {

        Integer pageSize = Integer.parseInt(request.getParameter("page"));
        String queryParam = request.getParameter("queryParams");
        String text = request.getParameter("text");

        HashMap<String, Object> queryParams = new HashMap<String, Object>();
        if (text != null && !"".equals(text)) {
            queryParams.put("%," + queryParam, text);
        }
        queryParams.put("^,sort", "asc");
        Integer count = iWordService.getThesauriWordModuleCount(queryParams);
        int page = (int) Math.ceil(Double.valueOf(count) / 9);
        LinkedHashMap<String, Object> r = new LinkedHashMap<String, Object>();
        List<ThesauriWordModule> list = iWordService.getThesauriWordModule(queryParams, pageSize,9);
        List<LinkedHashMap<String, Object>> wordList = new ArrayList<LinkedHashMap<String,Object>>();
        LinkedHashMap<String, Object> wordMap = null;
        for (int i = 0; i < list.size(); i++) {
            wordMap = new LinkedHashMap<String, Object>();
            ThesauriWordModule thesauriWordModule = list.get(i);
            HashMap<String, Object> queryWordParams = new LinkedHashMap<String, Object>();
            queryWordParams.put("=,thesauri_word_module_id", thesauriWordModule.getId());
            Integer  WordCount = iWordService.getThesauriWordCount(queryWordParams);
            wordMap.put("nameZh", thesauriWordModule.getNameZh());
            wordMap.put("nameEn", thesauriWordModule.getNameEn());
            wordMap.put("id", thesauriWordModule.getId());
            wordMap.put("description", thesauriWordModule.getDescription());
            wordMap.put("count", WordCount);
            wordList.add(wordMap);
        }
        r.put("count", count);
        r.put("page", page);
        r.put("list", wordList);
        String resultString = formatToJson(r);
        super.pringWriterToPage(resultString, "application/json", response);
    }
    //新增或修改分类
    @RequestMapping("addOrUploadWordModule")
    public void addOrUploadWordModule(HttpServletRequest request,HttpServletResponse response) throws Exception {
        String id = request.getParameter("id");
        String nameZh = request.getParameter("nameZh");
        String nameEn = request.getParameter("nameEn");
        String sort = request.getParameter("sort");
        String description = request.getParameter("description");
        
        ThesauriWordModule thesauriWordModule = new ThesauriWordModule();
        thesauriWordModule.setNameZh(nameZh);
        thesauriWordModule.setNameEn(nameEn);
        thesauriWordModule.setSort(Integer.parseInt(sort));
        thesauriWordModule.setDescription(description);
        String rString = "yes";
        try {
            if(id != null && !"".equals(id) && !"0".equals(id)){
                thesauriWordModule.setId(Integer.parseInt(id));
                iWordService.editThesauriWordModule(thesauriWordModule);
            }else{
                iWordService.saveThesauriWordModule(thesauriWordModule);
            }
        } catch (Exception e) {
            rString = "no";
            e.printStackTrace();
        }
        LinkedHashMap<String, String> r = new LinkedHashMap<String, String>();
        r.put("data", rString);
        String resultString = formatToJson(r);
        super.pringWriterToPage(resultString, "application/json", response);
    }
    //查询分类
    @RequestMapping("queryWordModule")
    public void queryWordModule(HttpServletRequest request,HttpServletResponse response) throws Exception {
        String id = request.getParameter("id");
        ThesauriWordModule thesauriWordModule= iWordService.findThesauriWordModule(Integer.parseInt(id));
        String resultString = formatToJson(thesauriWordModule);
        super.pringWriterToPage(resultString, "application/json", response);
    }
    //删除分类
    @RequestMapping("deleteWordModule")
    public void deleteWordModule(HttpServletRequest request,HttpServletResponse response) throws Exception {
        String id = request.getParameter("id");
        String rString = "yes";
        try {
            ThesauriWordModule thesauriWordModule = iWordService.findThesauriWordModule(Integer.parseInt(id));
            iWordService.deleteThesauriWordModule(thesauriWordModule);
        } catch (Exception e) {
            rString = "no";
            e.printStackTrace();
        }
        
        LinkedHashMap<String, String> r = new LinkedHashMap<String, String>();
        r.put("data", rString);
        String resultString = formatToJson(r);
        super.pringWriterToPage(resultString, "application/json", response);
    }
    /** 词表分类  end */
    
    /**
     * @author zf
     * 时间 2017年8月31日16:04:05
     * 词表模板  start
     */
    // 知识百科管理 -->模板管理查询分类
    @RequestMapping("relationQueryWordModule")
    public void relationQueryWordModule(HttpServletResponse response)
            throws Exception {

        List<ThesauriWordModule> list = iWordService.getThesauriWordModule();
        List<HashMap<String, Object>> r = new ArrayList<HashMap<String, Object>>();
        LinkedHashMap<String, Object> mp = null;
        for (int i = 0; i < list.size(); i++) {
            ThesauriWordModule thesauriWordModule = list.get(i);
            mp = new LinkedHashMap<String, Object>();
            mp.put("id", thesauriWordModule.getId());
            mp.put("name", thesauriWordModule.getNameZh());
            mp.put("pId", 0);
            r.add(mp);
        }
        String result = formatToJson(r);
        super.pringWriterToPage(result.toString(), "application/json", response);
    }
    //查询分类下模板
    @RequestMapping("getWordRelationList")
    public void getWordRelationList(HttpServletRequest request,HttpServletResponse response) throws Exception {
        String id = request.getParameter("id");
        String page = request.getParameter("page");
        HashMap<String, Object> queryParams = new LinkedHashMap<String, Object>();
        queryParams.put("=,thesauri_word_module_id", id);
        queryParams.put("^,sort", "asc");
        int count = iWordService.getThesauriWordRelationCount(queryParams);
        List<ThesauriWordRelation> thesauriWordRelationList=iWordService.getThesauriWordRelation(queryParams,Integer.parseInt(page), 15);
        HashMap<String, Object> r = new HashMap<String, Object>();
        r.put("data", thesauriWordRelationList);
        r.put("count", (int)Math.ceil(Double.valueOf(count)/15));
        String resultString = formatToJson(r);
        super.pringWriterToPage(resultString, "application/json", response);
    }
    //新增或修改分类
    @RequestMapping("addOrUploadWordRelation")
    public void addOrUploadWordRelation(HttpServletRequest request,HttpServletResponse response) throws Exception {
        String moduleId = request.getParameter("moduleId");
        String nameZh = request.getParameter("nameZh");
        String nameEn = request.getParameter("nameEn");
        String sort = request.getParameter("sort");
        String description = request.getParameter("description");
        String wordRelationId = request.getParameter("wordRelationId");
        
        ThesauriWordRelation thesauriWordRelation = new ThesauriWordRelation();
        thesauriWordRelation.setNameZh(nameZh);
        thesauriWordRelation.setNameEn(nameEn);
        thesauriWordRelation.setSort(Integer.parseInt(sort));
        thesauriWordRelation.setDescription(description);
        thesauriWordRelation.setThesauriWordModuleId(Integer.parseInt(moduleId));
        String rString = "yes";
        try {
            if(wordRelationId != null && !"".equals(wordRelationId) && !"0".equals(wordRelationId)){
                thesauriWordRelation.setId(Integer.parseInt(wordRelationId));
                iWordService.editThesauriWordRelation(thesauriWordRelation);
            }else{
                iWordService.saveThesauriWordRelation(thesauriWordRelation);
            }
        } catch (Exception e) {
            rString = "no";
            e.printStackTrace();
        }
        LinkedHashMap<String, String> r = new LinkedHashMap<String, String>();
        r.put("data", rString);
        String resultString = formatToJson(r);
        super.pringWriterToPage(resultString, "application/json", response);
    }
    //查询分类
    @RequestMapping("queryWordRelation")
    public void queryWordRelation(HttpServletRequest request,HttpServletResponse response) throws Exception {
        String id = request.getParameter("id");
        ThesauriWordRelation thesauriWordRelation= iWordService.findThesauriWordRelation(Integer.parseInt(id));
        String resultString = formatToJson(thesauriWordRelation);
        super.pringWriterToPage(resultString, "application/json", response);
    }
    //删除分类
    @RequestMapping("deleteWordRelation")
    public void deleteWordRelation(HttpServletRequest request,HttpServletResponse response) throws Exception {
        String id = request.getParameter("id");
        String rString = "yes";
        try {
            ThesauriWordRelation thesauriWordRelation = iWordService.findThesauriWordRelation(Integer.parseInt(id));
            iWordService.deleteThesauriWordRelation(thesauriWordRelation);
        } catch (Exception e) {
            rString = "no";
            e.printStackTrace();
        }
        
        LinkedHashMap<String, String> r = new LinkedHashMap<String, String>();
        r.put("data", rString);
        String resultString = formatToJson(r);
        super.pringWriterToPage(resultString, "application/json", response);
    }
    /** 词表模板  end */
    //展开或隐藏
    @RequestMapping("shouOrHeidWords")
    public void shouOrHeidWords(HttpServletRequest request,HttpServletResponse response) throws Exception {
        String wordReference = request.getParameter("wordReference");
        String wordId = request.getParameter("wordId");
        List<ThesauriWord> r = new ArrayList<ThesauriWord>();
        HashMap<String, Object> queryParams = new LinkedHashMap<String, Object>();
        queryParams.put("=,thesauri_word_id", wordId);
        queryParams.put("=,reference_relation_label", wordReference);
        List<ThesauriWordReference> thesauriWordReferenceList = iWordService.getThesauriWordReference(queryParams, 1, iWordService.getThesauriWordReferenceCount(queryParams));
        for (int i = 0; i < thesauriWordReferenceList.size(); i++) {
            ThesauriWordReference thesauriWordReference = thesauriWordReferenceList.get(i);
            ThesauriWord thesauriWord = iWordService.findThesauriWord(Integer.parseInt(thesauriWordReference.getReferenceWordId()));
            r.add(thesauriWord);
        }
        String resultString = formatToJson(r);
        super.pringWriterToPage(resultString, "application/json", response);
    }
    
    //叙词表发布
    @RequestMapping("releaseFindThesauriWord")
    public void releaseFindThesauriWord(HttpServletRequest request,HttpServletResponse response) throws Exception {
        String thesauriWordId = request.getParameter("thesauriWordId");
        HashMap<String, Object> r = new LinkedHashMap<String, Object>();
        try {
			dynamicService.submitThesauriWordIndex(thesauriWordId);
			r.put("data", "yes");
		} catch (Exception e) {
			r.put("data", "no");
		}
        String resultString = formatToJson(r);
        super.pringWriterToPage(resultString, "application/json", response);
    }
    //普通词表发布
    @RequestMapping("releaseFindGeneralWordId")
    public void releaseFindGeneralWordId(HttpServletRequest request,HttpServletResponse response) throws Exception {
        String generalWordId = request.getParameter("generalWordId");
        HashMap<String, Object> r = new LinkedHashMap<String, Object>();
        try {
			dynamicService.submitGeneralWordIndex(generalWordId);
			r.put("data", "yes");
		} catch (Exception e) {
			r.put("data", "no");
		}
        String resultString = formatToJson(r);
        super.pringWriterToPage(resultString, "application/json", response);
    }
	// 普通词表导出XML
	@RequestMapping("exportXmlGeneralWord")
	public void exportXmlGeneralWord(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String wordCategoryid = request.getParameter("wordCategoryid");
		DocumentBuilderFactory fct = DocumentBuilderFactory.newInstance();
		DocumentBuilder bui;
		try {
			// 驱动
			bui = fct.newDocumentBuilder();
			// 创建对象
			Document doc = bui.newDocument();
			// 设置根目录
			Element general_word_data = doc.createElement("general_word_data");
			List<GeneralWord> generalWords = null;
			if (wordCategoryid.equals("undefined")) {
				Integer cont1 = iWordService.getGeneralWordCount(null);
				generalWords = iWordService.getGeneralWord(null, 1, cont1);
			} else {
				HashMap<String, Object> queryParams = new HashMap<String, Object>();
				queryParams.put("=,generalWordCategoryId", wordCategoryid);
				Integer cont1 = iWordService.getGeneralWordCount(queryParams);
				generalWords = iWordService.getGeneralWord(queryParams, 1,cont1);
			}
			for (GeneralWord gl : generalWords) {
				// 设置二级目录
				Element general_word = doc.createElement("general_word");

				// 二级标题属性
				Attr id = doc.createAttribute("id");
				// 赋值

				id.setNodeValue(gl.getId().toString());
				// 写入二级目录
				general_word.setAttributeNode(id);
				if (null != gl.getWordScopeNote() && !gl.getWordScopeNote().equals("")) {
					Element word_scope_note = doc.createElement("word_scope_note");
					word_scope_note.setTextContent(gl.getWordScopeNote());
					general_word.appendChild(word_scope_note);
				}
//				 将节点写入二级目录
				if (null != gl.getWordName() && !gl.getWordName().equals("")) {
					Element word_name = doc.createElement("word_name");
					word_name.setTextContent(gl.getWordName());
					general_word.appendChild(word_name);
				}
				if (null != gl.getWordPinyin() && !gl.getWordPinyin().equals("")) {
					Element word_pinyin = doc.createElement("word_pinyin");
					word_pinyin.setTextContent(gl.getWordPinyin());
					general_word.appendChild(word_pinyin);
				}
				if (null != gl.getWordEnglish() && !gl.getWordEnglish().equals("")) {
					Element word_english = doc.createElement("word_english");
					word_english.setTextContent(gl.getWordEnglish());
					general_word.appendChild(word_english);
				}
				if (null != gl.getWordInitial() && !gl.getWordInitial().equals("")) {
					Element word_initial = doc.createElement("word_initial");
					word_initial.setTextContent(gl.getWordInitial());
					general_word.appendChild(word_initial);
				}
				GeneralWordCategory list = iWordService.findGeneralWordCategory(gl.getGeneralWordCategoryId());
				// 创建三级目录
				Element general_word_category = doc
						.createElement("general_word_category");
				// 属性
				Attr data_id = doc.createAttribute("data_id");
				data_id.setNodeValue(list.getId().toString());
				general_word_category.setAttributeNode(data_id);

				// 节点
				Element category_name = doc.createElement("category_name");
				category_name.setTextContent(list.getCategoryName());

				Element category_sid = doc.createElement("category_sid");
				category_sid.setTextContent(list.getCategorySid());
				// 赋值
				general_word_category.appendChild(category_name);
				general_word_category.appendChild(category_sid);
				// 写入上级目录
				general_word.appendChild(general_word_category);

				// 写入上级目录
				general_word_data.appendChild(general_word);
			}
			// 目录保存到doc
			doc.appendChild(general_word_data);

			// step9:获得一个TransformerFactory对象
			TransformerFactory transformerFactory = TransformerFactory
					.newInstance();
		
			// step10:获得一个Transformer对象
			Transformer transformer = transformerFactory.newTransformer();
			// step11:把document对象用一个DOMSource对象包装起来
			Source xmlSource = new DOMSource(doc);
			// 获取服务器地址
			ServletContext sc = request.getSession().getServletContext();
			String dir = sc.getRealPath("/XMLFile/");
			File dirFile = new File(dir);
			if (!dirFile.exists()) {
				dirFile.mkdirs();
			}

			String random = System.nanoTime() + ".xml";
			File downFile = new File(dirFile, random);
			Result outputTarget = new StreamResult(downFile);
			// step13:生成相应的xml文件
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
			transformer.setOutputProperty(
					"{http://xml.apache.org/xslt}indent-amount", "4");
			transformer.transform(xmlSource, outputTarget);

			// 下载文件
			FileDownloadUtil.download(downFile, "普通词表.xml", request, response);

		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	// 普通词表导出Excel
	@RequestMapping("exportExcelGeneralWord")
	public void exportExcelWord(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		response.setCharacterEncoding("utf-8");
		response.setContentType("multipart/form-data");
		String wordCategoryid = request.getParameter("id");
		String path =  XxlConfClient.get("dal.file.path", "") +"/";
		List<GeneralWord> generalWords = null;
		if (wordCategoryid.equals("undefined")) {
			Integer cont1 = iWordService.getGeneralWordCount(null);
			generalWords = iWordService.getGeneralWord(null, 1, cont1);
		} else {
			HashMap<String, Object> queryParams = new HashMap<String, Object>();
			queryParams.put("=,generalWordCategoryId", wordCategoryid);
			Integer cont1 = iWordService.getGeneralWordCount(queryParams);
			generalWords = iWordService.getGeneralWord(queryParams, 1,cont1);
		}
		List<HashMap<String, Object>> generalWordCategoryData = new ArrayList<HashMap<String, Object>>();
		GeneralWordCategory generalWordCategory=iWordService.findGeneralWordCategory(Integer.parseInt(wordCategoryid));
		HashMap<String, Object> mapGeneralWord = new HashMap<String, Object>();
		mapGeneralWord.put("category_name",generalWordCategory.getCategoryName());
		mapGeneralWord.put("category_sid", generalWordCategory.getCategorySid());
		generalWordCategoryData.add(mapGeneralWord);
		List<HashMap<String, Object>> listData = new ArrayList<HashMap<String, Object>>();
		HashMap<String, Object> map = null;
		for (int i = 0; i < generalWords.size(); i++) {
			GeneralWord generalWord= generalWords.get(i);
			map = new HashMap<String, Object>();
			map.put("general_word_category_id", (null != generalWord.getGeneralWordCategoryId()) ? generalWord.getGeneralWordCategoryId() : "");
			map.put("word_name", (null != generalWord.getWordName()) ? generalWord.getWordName() : "");
			map.put("word_pinyin", (null != generalWord.getWordPinyin()) ? generalWord.getWordPinyin() : "");
			map.put("word_english", (null != generalWord.getWordEnglish()) ? generalWord.getWordEnglish() : "");
			map.put("word_initial", (null != generalWord.getWordInitial()) ? generalWord.getWordInitial() : "");
			map.put("word_scope_note", (null != generalWord.getWordScopeNote()) ? generalWord.getWordScopeNote() : "");
			listData.add(map);
		}
		HashMap<String, List<HashMap<String, Object>>> excelMap = new HashMap<String, List<HashMap<String, Object>>>();
		excelMap.put("分类", generalWordCategoryData);
		excelMap.put("普通词表", listData);
		ExcelMore.writeExcelListMore(path+"export.xlsx", excelMap, 1);
		downloadkk(request, response,"export.xlsx", path);
	}
	//下载EXCEL
public void downloadkk(HttpServletRequest request,
			HttpServletResponse response, String fileName, String path)
			throws Exception {
		response.setCharacterEncoding("utf-8");
		response.setContentType("multipart/form-data");
		response.setHeader("Content-Disposition", "attachment;fileName="
				+ fileName);
		try {
			// 这个download目录为啥建立在classes下的
			InputStream inputStream = new FileInputStream(new File(path + "/"
					+ File.separator + fileName));
			OutputStream os = response.getOutputStream();
			byte[] b = new byte[2048];
			int length;
			while ((length = inputStream.read(b)) > 0) {
				os.write(b, 0, length);
			}
			// 这里主要关闭。
			os.close();
			inputStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	//导入
	@RequestMapping("importGeneralWord")
	public void importWord(HttpServletRequest request,HttpServletResponse response) throws Exception {
		String urlFile = request.getParameter("urlFile");
		//访问前缀	
		String uploadPath =  XxlConfClient.get("dal.file.server", "") +"/";
		//磁盘前缀
		String adjunctPath =  XxlConfClient.get("dal.file.path", "");
		LinkedHashMap<String, Object> r = new LinkedHashMap<String, Object>();
		
		urlFile = urlFile.replaceAll(uploadPath, "");
		String lastType = urlFile.substring(urlFile.lastIndexOf(".")+1, urlFile.length());
		try {
			if("xml".equals(lastType)){
				String rXml = this.importWordXml(request, response);
				r.put("data", rXml);
			}else if("xls".equals(lastType) || "xlsx".equals(lastType)){
				String rExcel = this.importWordExcel(adjunctPath+"/"+urlFile);
				System.out.println(rExcel);
				r.put("data", rExcel);
			}else{
				r.put("data", "type");
			}
		} catch (Exception e) {
			e.printStackTrace();
			r.put("data", "no");
		}
		String result = formatToJson(r);
		super.pringWriterToPage(result.toString(), "application/json", response);
	}
	//普通词表导入Excel
	public String importWordExcel(String path) throws Exception{
		List<Map<String, Object>> dataCategory = ExcelMore.readExcel(path,"分类");
		List<Map<String, Object>> dataGWord = ExcelMore.readExcel(path,"普通词表");
		GeneralWordCategory aGeneralWordCategory=null;
		Integer cont1 = iWordService.getGeneralWordCategoryCount(null);
		List<GeneralWordCategory> generalWordCategorys = iWordService.getGeneralWordCategory(null, 1, cont1);
		String r = "yes";
		int aa=0;
		try {
			HashMap<String, Object> queryParams1 = null;
			for (int i = 0; i < dataCategory.size(); i++) {
				Map<String, Object> categoryMap = dataCategory.get(i);
				GeneralWordCategory generalWordCategory=new GeneralWordCategory();
				generalWordCategory.setCategoryName(categoryMap.get("category_name").toString());
				generalWordCategory.setCategorySid(categoryMap.get("category_sid").toString());
				for (int j = 0; j < generalWordCategorys.size(); j++) {
					if(generalWordCategorys.get(j).getCategorySid().toString().equals(generalWordCategory.getCategorySid())){
						aa=1;
					}
				}
				if(aa==0){
					iWordService.saveGeneralWordCategory(generalWordCategory);
				}
				queryParams1 = new HashMap<String, Object>();
				queryParams1.put("=,category_sid", categoryMap.get("category_sid").toString());
				List<GeneralWordCategory> generalWordCategoryList = iWordService.getGeneralWordCategory(queryParams1, 1, 1);
				aGeneralWordCategory=generalWordCategoryList.get(0);
			}
			HashMap<String, Object> queryParams = null;
			for (int i = 0; i < dataGWord.size(); i++) {
				Map<String, Object> generalWordMap = dataGWord.get(i);
				GeneralWord generalWord=new GeneralWord();
				generalWord.setWordName(generalWordMap.get("word_name").toString());
				generalWord.setGeneralWordCategoryId(Integer.parseInt(generalWordMap.get("general_word_category_id").toString()));
				generalWord.setWordEnglish(generalWordMap.get("word_english").toString());
				generalWord.setWordInitial(generalWordMap.get("word_initial").toString());
				generalWord.setWordPinyin(generalWordMap.get("word_pinyin").toString());
				generalWord.setWordScopeNote(generalWordMap.get("word_scope_note").toString());
				if(null != generalWordMap.get("word_name") && !"".equals(generalWordMap.get("word_name"))){
					queryParams = new HashMap<String, Object>();
					queryParams.put("=,word_name", generalWordMap.get("word_name"));
					List<GeneralWord> generalWordList=iWordService.getGeneralWord(queryParams, 1, 1);
					if(null != generalWordList && generalWordList.size()>0 ){
						generalWord.setGeneralWordCategoryId(aGeneralWordCategory.getId());
					}
				}
				iWordService.saveGeneralWord(generalWord);
			}
		} catch (Exception e) {
			e.printStackTrace();
			r = "no";
		}
		return r;
	}
	//普通词表导入XML
	public String importWordXml(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String r="yes";
		try {
			//访问前缀	
			String uploadPath =  XxlConfClient.get("dal.file.server", "") +"/";
			//磁盘前缀
			String adjunctPath =  XxlConfClient.get("dal.file.path", "");
			// 解析文件，生成document对象
			String path = request.getParameter("urlFile");
			DocumentBuilder builder = DocumentBuilderFactory.newInstance()
					.newDocumentBuilder();
			path = path.replaceAll(uploadPath, "");
			Document document = builder.parse(new File(adjunctPath+path));

			// 生成XPath对象
			XPath xpath = XPathFactory.newInstance().newXPath();

			// 获取节点集合
			NodeList f_subject = (NodeList) xpath.evaluate("//general_word",
					document, XPathConstants.NODESET);
			for (int i = 0; i < f_subject.getLength(); i++) {
				Node subject = f_subject.item(i);
				// 属性id
				String iddata = xpath.evaluate("@id", subject,
						XPathConstants.STRING).toString();
				// 一级所有值
				String word_name = xpath.evaluate("word_name", subject,
						XPathConstants.STRING).toString();
				String word_pinyin = xpath.evaluate("word_pinyin", subject,
						XPathConstants.STRING).toString();
				String word_english = xpath.evaluate("word_english", subject,
						XPathConstants.STRING).toString();
				String word_initial = xpath.evaluate("word_initial", subject,
						XPathConstants.STRING).toString();
				String word_scope_note = xpath.evaluate("word_scope_note", subject,
						XPathConstants.STRING).toString();
				NodeList general_word_category = (NodeList) xpath.evaluate(
						"general_word_category", subject, XPathConstants.NODESET);

				// 二级节点内容
				String category_name = "";
				String category_sid = "";
				String category_dataid = "";
				for (int j = 0; j < general_word_category.getLength(); j++) {
					Node subjectWord = general_word_category.item(j);
					// 二级节点所以值
					category_name = xpath.evaluate("category_name", subjectWord,
							XPathConstants.STRING).toString();
					category_sid = xpath.evaluate("category_sid", subjectWord,
							XPathConstants.STRING).toString();

					// 二级节点属性
					category_dataid = xpath.evaluate("@data_id", subjectWord,
							XPathConstants.STRING).toString();

				}

				// 词表分类
				Integer count = iWordService.getGeneralWordCount(null);
				boolean falg2 = true;

				List<GeneralWordCategory> generalWordCategories = iWordService
						.getGeneralWordCategory();
				for (int k = 0; k < generalWordCategories.size(); k++) {
					GeneralWordCategory generalWordCategory = generalWordCategories
							.get(k);
					if (generalWordCategory.getCategoryName().equals(category_name)) {
						falg2 = false;
						break;// 插重，不插入。
					}
				}
				if (falg2) {
					GeneralWordCategory generalWordCategory = new GeneralWordCategory();

					generalWordCategory.setCategoryName(category_name);
					generalWordCategory.setCategorySid(category_sid);
					
					generalWordCategory.setId(Integer.parseInt(category_dataid));
					iWordService.saveGeneralWordCategory(generalWordCategory);

				}
				GeneralWordCategory generalWordCategory2 = new GeneralWordCategory();
				List<GeneralWordCategory> generalWordCategories2 = iWordService
						.getGeneralWordCategory();
				for (int k = 0; k < generalWordCategories2.size(); k++) {
					GeneralWordCategory generalWordCategory = generalWordCategories2
							.get(k);
					if (generalWordCategory.getCategoryName().equals(category_name)) {
						generalWordCategory2 = generalWordCategories2.get(k);
						break;// 插重，不插入。
					}
				}
				// 词表插入
				Integer cont2 = iWordService.getGeneralWordCount(null);

				List<GeneralWord> generalWords = iWordService.getGeneralWord(null,
						1, cont2);
				boolean falg = true;
				for (int j = 0; j < generalWords.size(); j++) {
					GeneralWord generalWord = generalWords.get(j);
					if (generalWord.getWordName().equals(word_name))// 查重,false不插入
					{
						falg = false;
						break;
					}
				}
				if (falg) {
					GeneralWord generalWord = new GeneralWord();
					generalWord.setWordName(word_name);
					generalWord.setWordPinyin(word_pinyin);
					generalWord.setWordEnglish(word_english);
					generalWord.setWordInitial(word_initial);
					generalWord.setWordScopeNote(word_scope_note);
					generalWord.setGeneralWordCategoryId(generalWordCategory2
							.getId());
					iWordService.saveGeneralWord(generalWord);

				}
			}
			
		} catch (Exception e) {
			r="no";
		}
	return r;
	}
}
